package com.openmanus.config.persistence;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.openmanus.config.OpenManusProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * MyBatis-Plus 配置类
 * 当选择MyBatis-Plus作为ORM框架时启用
 * 
 * @author OpenManus Team
 * @version 1.0.0
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(name = "openmanus.persistence.orm", havingValue = "mybatis-plus")
@MapperScan(basePackages = "com.openmanus.**.mapper")
@EnableTransactionManagement
public class MyBatisPlusConfiguration {

    private final OpenManusProperties properties;

    /**
     * MyBatis-Plus 拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        OpenManusProperties.PersistenceProperties.DatabaseType dbType = 
                properties.getPersistence().getDatabase();
        
        log.info("启用MyBatis-Plus持久化配置: 数据库类型={}", dbType.getName());

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 分页插件
        DbType mybatisPlusDbType = switch (dbType) {
            case POSTGRESQL -> DbType.POSTGRE_SQL;
            case MYSQL -> DbType.MYSQL;
            case H2 -> DbType.H2;
        };
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(mybatisPlusDbType));
        
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        
        return interceptor;
    }
}
